import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:private_journey/DataSets.dart';
import 'package:private_journey/States.dart';
import 'package:private_journey/components/LinkItemContainer.dart';
import 'package:private_journey/components/SearchComponent.dart';
import 'package:private_journey/components/TimeComponent.dart';
import 'package:private_journey/services/BackgroundImageService.dart';
import 'package:private_journey/services/DbService.dart';
import 'package:private_journey/services/RandomTextService.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shadcn;
import 'package:signals/signals_flutter.dart';

import 'AddNewIconPage.dart';

class TrendingPage extends StatefulWidget {
  const TrendingPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return TrendingPageState();
  }
}

class LinkInfo {
  final int id;
  final String icon;
  final String text;
  final String url;

  LinkInfo({
    required this.id,
    required this.icon,
    required this.text,
    required this.url,
  });

  @override
  String toString() {
    return 'LinkInfo{id: $id, icon: $icon, text: $text, url: $url}';
  }
}

class TrendingPageState extends State<TrendingPage> {
  int people = 0;
  bool showBookmarksBar = false;
  bool showFullUrls = true;

  void fetchHitokoto() async {
    var res = await RandomTextService.randomText();
    hitokoto.value = res.hitokoto;
  }

  Future<void> fetchDb() async {
    DbService dbService = DbService();
    var db = await dbService.database;
    List<Map> listm = await db.rawQuery('select * from my_sites');
    var sss = <LinkInfo>[];
    for (var item in listm) {
      sss.add(
        LinkInfo(
          id: item['id'],
          icon: item['icon_url'],
          text: item['site_name'],
          url: item['site_url'],
        ),
      );
    }
    if (mounted) {
      linkInfos.value = [...sss];
    }
  }

  void fetchBackgroundImage() async {
    var curImg = await BackgroundImageService.currentBackgroundImage();
    var list = await BackgroundImageService.fetchImages();
    backgroundImages = [...list];
    if (curImg.isNotEmpty) {
      BackgroundImageService.changeBackgroundImage(curImg);
    } else {
      BackgroundImageService.changeBackgroundImage(backgroundImages[0].url);
    }
  }

  @override
  void initState() {
    super.initState();
    fetchDb();
    fetchBackgroundImage();
    fetchHitokoto();
  }

  @override
  void dispose() {
    linkInfos.value = [];
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: shadcn.ContextMenu(
          behavior: HitTestBehavior.opaque,
          items: [
            shadcn.MenuButton(
              onPressed: (context) {
                BackgroundImageService.changeBackgroundImage(
                  backgroundImages[++currentBckImgIndex %
                          backgroundImages.length]
                      .url,
                );
              },
              trailing: shadcn.MenuShortcut(
                activator: SingleActivator(
                  LogicalKeyboardKey.bracketLeft,
                  control: true,
                ),
              ),
              child: Text('更换背景图片'),
            ),
            const shadcn.MenuButton(
              trailing: shadcn.MenuShortcut(
                activator: SingleActivator(
                  LogicalKeyboardKey.bracketRight,
                  control: true,
                ),
              ),
              enabled: false,
              child: Text('添加卡片'),
            ),
            const shadcn.MenuButton(
              trailing: shadcn.MenuShortcut(
                activator: SingleActivator(
                  LogicalKeyboardKey.keyR,
                  control: true,
                ),
              ),
              child: Text('Reload'),
            ),
            const shadcn.MenuButton(
              subMenu: [
                shadcn.MenuButton(
                  trailing: shadcn.MenuShortcut(
                    activator: SingleActivator(
                      LogicalKeyboardKey.keyS,
                      control: true,
                    ),
                  ),
                  child: Text('Save Page As...'),
                ),
                shadcn.MenuButton(child: Text('Create Shortcut...')),
                shadcn.MenuButton(child: Text('Name Window...')),
                shadcn.MenuDivider(),
                shadcn.MenuButton(child: Text('Developer Tools')),
              ],
              child: Text('More Tools'),
            ),
            const shadcn.MenuDivider(),
            shadcn.MenuCheckbox(
              value: showBookmarksBar,
              onChanged: (context, value) {
                setState(() {
                  showBookmarksBar = value;
                });
              },
              autoClose: false,
              trailing: const shadcn.MenuShortcut(
                activator: SingleActivator(
                  LogicalKeyboardKey.keyB,
                  control: true,
                  shift: true,
                ),
              ),
              child: const Text('Show Bookmarks Bar'),
            ),
            shadcn.MenuCheckbox(
              value: showFullUrls,
              onChanged: (context, value) {
                setState(() {
                  showFullUrls = value;
                });
              },
              autoClose: false,
              child: const Text('Show Full URLs'),
            ),
            const shadcn.MenuDivider(),
            const shadcn.MenuLabel(child: Text('People')),
            const shadcn.MenuDivider(),
            shadcn.MenuRadioGroup(
              value: people,
              onChanged: (context, value) {
                setState(() {
                  people = value;
                });
              },
              children: const [
                shadcn.MenuRadio(
                  value: 0,
                  autoClose: false,
                  child: Text('Pedro Duarte'),
                ),
                shadcn.MenuRadio(
                  value: 1,
                  autoClose: false,
                  child: Text('Colm Tuite'),
                ),
              ],
            ),
          ],
          child: Watch((context) {
            return shadcn.Container(
              padding: const shadcn.EdgeInsets.all(5),
              decoration: shadcn.BoxDecoration(
                image:
                    userBackGroundImage.value == ''
                        ? null
                        : DecorationImage(
                          image: NetworkImage(userBackGroundImage.value),
                          fit: BoxFit.cover,
                          opacity: 0.5,
                        ),
              ),
              child: Column(
                children: [
                  TimeComponent(),
                  SearchComponent(),
                  LinkItemContainer(),
                  shadcn.Container(child: Text(hitokoto.value)),
                ],
              ),
            );
          }),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          shadcn.showDialog(
            context: context,
            builder: (context) {
              return AddNewIconPage();
            },
          );
        },
      ),
    );
  }
}
